package com.example.userserver.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.commons.entity.UserDO;
import com.example.userserver.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
//@AllArgsConstructor
public class CustomAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

  //  private final UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取 前端传过来的用户名和密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        // 效验用户名和密码是否为空
        if (StringUtils.isEmpty(username)){
            throw new NullPointerException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)){
            throw new NullPointerException("密码不能为空");
        }
        // 根据 当前用户名 获取数据库 用户信息
        QueryWrapper<UserDO> userDOQueryWrapper=new QueryWrapper<>();
        userDOQueryWrapper.eq("username",username);
        UserDO user = userService.getOne(userDOQueryWrapper);
        //UserDO user = userMapper.getUserByName(username);
        if (null == user){
            throw new NullPointerException("该用户不存在");
        }
        //  principal：认证的实体信息，可以是username，也可以是数据库表对应的用户的实体对象
        // shiro 效验凭证
        Object credentials = user.getPassword();
        // 加盐 用户密码加密时用到
       // ByteSource credentialsSalt = ByteSource.Util.bytes("zh");
        ByteSource salt = new Sha256Hash(user.getSalt());
      //  return new SimpleAuthenticationInfo(principal,credentials,user.getSalt(),this.getClass().getName());
        return new SimpleAuthenticationInfo(user, credentials, salt, getName());
    }
}
